from rest_framework.mixins import ListModelMixin, CreateModelMixin, DestroyModelMixin, UpdateModelMixin
from response import APIResponse
from status import *


class MyListModelMixin(ListModelMixin):
    """
    List a queryset.
    """

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return APIResponse(code=SUCCESS, msg="获取成功", data=serializer.data)


class MyDestroyModelMixin(DestroyModelMixin):
    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        response = self.perform_destroy(instance)
        return response or APIResponse(code=SUCCESS, msg="删除成功")

    def perform_destroy(self, instance):
        instance.is_deleted = True
        instance.save()


class MyCreateModelMixin(CreateModelMixin):
    def create(self, request, *args, **kwargs):
        res = self.get_serializer(data=request.data)
        if res.is_valid():
            self.perform_create(res)
            return APIResponse(code=SUCCESS, msg="创建成功")

        return APIResponse(code=ERROR, msg=res.errors)


class MyUpdateModelMixin(UpdateModelMixin):
    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        pk = kwargs.pop("pk")
        instance = self.get_object()
        res = self.get_serializer(instance, data=request.data, partial=partial,
                                  context={'request': request, "pk": pk})
        if res.is_valid():
            response = self.perform_update(res)
            print(response)
            if getattr(instance, '_prefetched_objects_cache', None):
                instance._prefetched_objects_cache = {}
            return response or APIResponse(code=SUCCESS, msg="修改成功")
        return APIResponse(code=ERROR, msg=res.errors)
